package com.dmcb.trade.business.crawlers.article;

import com.dmcb.common.business.utils.DateUtil;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.entities.Article;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;

/**
 * 微信文章解析
 * Created by long on 2016/3/11.
 */
@Service
public class WeixinParser extends BaseParser {

    /**
     * 网站URL网址
     *
     * @return 链接
     */
    @Override
    protected String url() {
        return CrawlConstant.WEIXIN_URL;
    }

    /**
     * 获取标题选择器
     *
     * @return 标题选择器
     */
    @Override
    protected String titleSelect() {
        return "h2#activity-name";
    }

    /**
     * 获取日期选择器
     *
     * @return 发布日期选择器
     */
    @Override
    protected String dateSelect() {
        return "em#post-date";
    }

    /**
     * 获取正文内容选择器
     *
     * @return 正文内容选择器
     */
    @Override
    protected String bodySelect() {
        return "div#js_content";
    }

    /**
     * 获取封面选择器
     *
     * @return 封面选择器
     */
    @Override
    protected String coverSelect() {
        return "div#js_content>p>span img[src]";
    }

    /**
     * 获取封面选择器 多个
     *
     * @return 封面选择器
     */
    protected String coverSelectMulti() {
        return "div#js_content img[data-type~=(png|jpeg|jpg|gif)]";
    }

    /**
     * 获取作者选择器
     *div.rich_media_meta_list>em:not([id])
     * @return 作者选择器
     */
    @Override
    protected String authorNameSelect() {
        return "span.rich_media_meta_text";
    }

    @Override
    protected String platform() {
        return "微信";
    }


    @Override
    protected void setPostDate(Document doc, Article article) {
        String time = doc.toString();
        if(StringUtils.isBlank(time)){
            return;
        }
        time = time.substring(time.indexOf("var ct=\"")+8);
        time = time.substring(0,time.indexOf("\""));
        try {
            Date date = DateUtil.stampToDate(time);
            article.setPostTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void setAuthorName(Document doc, Article article) {
        Elements elements = doc.select("span.rich_media_meta_text");
        if(elements != null && elements.size()>1){
            String authorName = elements.last().text();
            authorName = authorName.trim().replace("编辑", "").replace("作者", "").replace("：", "").replace(":", "").replace("（原创）","");
            article.setAuthorName(authorName);
        }
    }

    @Override
    protected String imageType() {
        return "data-src";
    }

    @Override
    protected boolean isJsEnabled() {
        return true;
    }

    @Override
    protected boolean isProxyEnabled() {
        return true;
    }
}
